<template>
  <div class="ProButton">
    <Button
      v-for="item in props.options"
      :key="item"
      :type="defaultBtn.includes(item) ? 'default' : type"
      :loading="loading[item]"
      :danger="item === 'delete'"
      @click="handle(item)"
      >
      <a-popconfirm
          :disabled="! ['delete','disable','enable'].includes(item)"
          :title="t(`${message[item] || 'yes'}`)"
          :ok-text="t('yes')"
          :cancel-text="t('no')"
          @confirm="confirm(item)"
      >
        {{ t(item) }}
      </a-popconfirm>
    </Button
    >
  </div>
</template>

<script lang="ts" setup>
import type { ButtonProps } from "ant-design-vue";
import { Button } from "ant-design-vue";
import { onMounted, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { buttonType } from './interface';
const { t } = useI18n({inheritLocale: true,useScope: 'local'})
interface PropsType {
  type:ButtonProps['type'];
  options: buttonType[];
  finished:(params:buttonType)=> Promise<unknown>
  cancel:()=> void
}

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<PropsType>(), {
  type:"primary",
  options: () => ['submit', 'close'],
});

const loading = reactive<any>({})
const defaultBtn = ['close','reset']
const message:any = {
  disable:'is_disable',
  enable:'is_enable',
  delete:'is_delete'
}

onMounted(()=>{
  props.options.forEach((v)=>{
    loading[v] = false
  })
})

// const emit = defineEmits(['finished','cancel']);

const handle = (type:buttonType)=>{
  if(["disable" , "enable" , "delete"].includes(type)) return false
  if(defaultBtn.includes(type)) {
    handleCancel()
  }else{
    handleClose(type)
  }
}

const confirm = (type:buttonType)=>{
  if(defaultBtn.includes(type)) {
    handleCancel()
  }else{
    handleClose(type)
  }
}

const handleClose =  async(type: buttonType) => {
  try {
    loading[type] = true
    await props.finished(type)
    loading[type] = false
  }catch (e) {
    console.log(e)
    loading[type] = false
  }

};

const handleCancel = () => {
  props.cancel()
};

</script>

<i18n>
  {
    "en": {
      "submit":"Submit",
      "close":"Close",
      "link":"Link",
      "publish":"Publish",
      "save":"Save",
      "view":"View",
      "edit":"Edit",
      "delete":"Delete",
      "reset":"Reset",
      "add":"Add",
      "disable": "Disable",
      "enable": "Enable",
      "yes": "Yes",
      "no": "No",
      "is_disable": "Confirm Disabled",
      "is_enable": "Confirm Enable",
      "is_delete": "Confirm Delete"
    },
    "ch": {
      "submit":"提交",
      "close":"关闭",
      "link":"链接",
      "publish":"发布",
      "save":"保存",
      "view":"查看",
      "edit":"编辑",
      "delete":"删除",
      "reset":"重置",
      "add":"新增子级",
      "disable": "禁用",
      "enable": "启用",
      "yes": "确定",
      "no": "取消",
      "is_disable": "确定禁用？",
      "is_enable": "确定启用？",
      "is_delete": "确定删除？"
    }
  }
  </i18n>

<style lang="less" scoped>

</style>
